using System.ComponentModel;
using System.Reflection;

namespace SupplierCustomerManagement.Domain.Enums
{
    /// <summary>
    /// 枚举扩展方法类
    /// 提供枚举相关的辅助方法，如获取描述信息等
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取枚举的描述信息
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>描述信息，如果没有Description特性则返回枚举名称</returns>
        public static string GetDescription(this Enum enumValue)
        {
            var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
            return descriptionAttribute?.Description ?? enumValue.ToString();
        }

        /// <summary>
        /// 获取枚举的所有项及其描述
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>包含枚举值和描述的字典</returns>
        public static Dictionary<T, string> GetEnumDescriptions<T>() where T : Enum
        {
            var result = new Dictionary<T, string>();
            var enumType = typeof(T);
            
            foreach (T enumValue in Enum.GetValues(enumType))
            {
                result[enumValue] = enumValue.GetDescription();
            }
            
            return result;
        }

        /// <summary>
        /// 根据描述获取枚举值
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="description">描述信息</param>
        /// <returns>对应的枚举值，如果找不到则返回默认值</returns>
        public static T? GetEnumByDescription<T>(string description) where T : struct, Enum
        {
            var enumType = typeof(T);
            
            foreach (T enumValue in Enum.GetValues(enumType))
            {
                if (enumValue.GetDescription() == description)
                {
                    return enumValue;
                }
            }
            
            return null;
        }
    }
}